package com.jblog.article.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jblog.article.dao.CategoryDao;
import com.jblog.article.model.Category;
import com.jblog.common.exception.ParentDefinedException;
import com.jblog.common.exception.RecordAlreadyExistsException;
import com.jblog.common.exception.RecordNotFoundException;

@Service
public class CategoryServiceImpl implements CategoryService{

	@Autowired
	CategoryDao categoryDao;
	
	@Override
	@Transactional
	public void add(Category category) throws ParentDefinedException, RecordAlreadyExistsException {
		
		//如果类别已存在
		if(categoryDao.find(category.getId()) != null){
			throw new RecordAlreadyExistsException();
		}
		
		//当前类别不能与父类别重名
		Category parent = category.getParent();
		if(parent != null && category.getId().equals(parent.getId()))
			throw new ParentDefinedException();
		
		categoryDao.merge(category);
	}

	@Override
	public void update(Category category) throws ParentDefinedException {
		//当前类别不能与父类别重名
		Category parent = category.getParent();
		if(parent != null && category.getId().equals(parent.getId()))
			throw new ParentDefinedException();
		categoryDao.merge(category);
	}

	@Override
	public Category find(String id) throws RecordNotFoundException {
		return categoryDao.find(id);
	}
}
